package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	request "github.com/ifnk/micro-blog/internal/blog/dto/casbin_dto"
	"github.com/ifnk/micro-blog/internal/blog/global"
	response "github.com/ifnk/micro-blog/internal/pkg/http"
	"github.com/ifnk/micro-blog/internal/pkg/utils"
	"github.com/ifnk/micro-blog/protobuf/permission_pb"
	"go.uber.org/zap"
)

func InitCasbinController(r *gin.RouterGroup) {
	api := r.Group("/casbin")
	// 这个 要 使用 jwt 和 casbin 中间件
	//api.Use(middleware.JWTAuth())
	api.POST("updateCasbin", updateCasbin)
	api.POST("getPolicyPathByAuthorityId", getPolicyPathByAuthorityId)
}

//  更新角色api权限
func updateCasbin(c *gin.Context) {
	var cmr request.CasbinInReceive
	_ = c.ShouldBindJSON(&cmr)
	if err := utils.Verify(cmr, utils.AuthorityIdVerify); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//if err := global.CasbinClient.ModifyCasbin(cmr.AuthorityIds, cmr.CasbinInfos); err != nil {
	in := &permission_pb.UpdateCasbinRequest{AuthorityId: cmr.AuthorityId, CasbinInfos: cmr.CasbinInfos}
	_, err := global.CasbinClient.ModifyCasbin(c, in)
	if err != nil {
		global.Logger.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// @Summary 获取权限列表
func getPolicyPathByAuthorityId(c *gin.Context) {
	var input *permission_pb.GetPolicyPathByAuthorityIdRequest
	_ = c.ShouldBindJSON(&input)
	//if err := utils.Verify(input, utils.AuthorityIdVerify); err != nil {
	//	response.FailWithMessage(err.Error(), c)
	//	return
	//}
	req := &permission_pb.GetPolicyPathByAuthorityIdRequest{AuthorityId: input.AuthorityId}

	getPathsRes, err := global.CasbinClient.GetPolicyPathByAuthorityId(c, req)
	if err != nil {
		response.FailWithMessage(fmt.Sprintf("获取权限列表失败! -> %+v", err), c)
		return
	}
	response.OkWithDetailed(getPathsRes, "获取成功", c)
}
